package com.antdesignbackend.backend.common;

import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class ServletContextUtil {
    public ServletContextUtil() {
    }

    public static HttpServletRequest getRequest() {
        HttpServletRequest result = null;
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            ServletRequestAttributes servlet = (ServletRequestAttributes) attributes;
            result = servlet.getRequest();
        }

        return result;
    }

    public static HttpServletResponse getResponse() {
        HttpServletResponse result = null;
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            ServletWebRequest servlet = (ServletWebRequest) attributes;
            result = servlet.getResponse();
        }

        return result;
    }

    public static HttpSession getSession() {
        HttpSession result = null;
        HttpServletRequest request = getRequest();
        if (request != null) {
            result = request.getSession();
        }

        return result;
    }

    public static ServletContext getApplication() {
        ServletContext result = null;
        HttpServletRequest request = getRequest();
        if (request != null) {
            result = request.getServletContext();
        }

        return result;
    }

    public static Cookie[] getCookies() {
        Cookie[] result = null;
        HttpServletRequest request = getRequest();
        if (request != null) {
            result = request.getCookies();
        }

        return result;
    }

    public static String getSessionId() {
        String result = null;
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            ServletRequestAttributes servlet = (ServletRequestAttributes) attributes;
            result = servlet.getSessionId();
        }

        return result;
    }

    public static String getRequestId() {
        String result = null;
        HttpServletRequest request = getRequest();
        if (request == null) {
            return result;
        } else {
            Object requestId = request.getAttribute("sf_request_id");
            if (requestId == null) {
                return null;
            }

            return requestId.toString();
        }
    }
}
